package com.googlecode.sqldatagenerator.service.impl;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashSet;

import com.googlecode.sqldatagenerator.model.dto.DatabaseDto;
import com.googlecode.sqldatagenerator.model.dto.QueryDto;
import com.googlecode.sqldatagenerator.model.dto.TableDto;
import com.googlecode.sqldatagenerator.parser.SqlParser;
import com.googlecode.sqldatagenerator.service.SqlReaderService;
import com.googlecode.sqldatagenerator.util.Callback;

public class SqlReaderServiceImpl implements SqlReaderService {

    @Override
    public void parseScript(String sql, Callback<DatabaseDto> callback) {
        try {
            DatabaseDto database = new DatabaseDto();
            database.setTables(new HashSet<TableDto>());
            database.setQueries(new ArrayList<QueryDto>());

            SqlParser parser = new SqlParser(new StringReader(sql));        
            do {
                try {
                    QueryDto query = parser.parseSql();
                    database.getQueries().add(query);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }            
            } while (!parser.isEndOfFile());        

            callback.onSuccess(database);
        } catch (Exception e) {
            callback.onError(e);
        }
    }

}
